#include<stdbool.h>
#include<stdio.h>
#include "Stack.h"
#include <stdlib.h>



void Stack_Init_OPTR(OPTR* ptr) //初始化操作符符栈
{
	ptr->top = -1;
}

void Stack_Init_BiTree(stack_BiTree* ptr)//初始化二叉树栈
{
	ptr->top = -1;
}

bool JUdge_Stack_OPTR(OPTR* ptr)//判断操作符栈是否空
{
	if (ptr->top == -1)
	{
		return STACK_EMPTY;
	}
	else
		return 0;
}

bool JUdge_Stack_BiTree(stack_BiTree* ptr)//判断二叉树栈是否空
{
	if (ptr->top == -1)
	{
		return STACK_EMPTY;
	}
	else
		return 0;
}


void Stack_Push_OPTR(OPTR* stack, char new_element) //操作符入栈
{
	if (stack->top < STACK_SIZE - 1)
	{
		(stack->top)++;
		stack->element[stack->top] = new_element;
	}
	else
		printf("ERROR Push");

}

void Stack_Push_BiTree(stack_BiTree* stack, BiTreeNode NewNode) //二叉树结点入栈
{
	if (stack->top < STACK_SIZE - 1)
	{
		(stack->top)++;
		stack->element[stack->top].data = NewNode.data;
		stack->element[stack->top].leftChild = NewNode.leftChild;
		stack->element[stack->top].rightChild = NewNode.rightChild;
	}
	else
		printf("ERROR Push");

}


char Stack_Pop_OPTR(OPTR* stack) //从操作符栈顶取出一个元素
{
	char data;
	data = stack->element[stack->top];
	(stack->top)--;
	return data;
}

BiTree Stack_Pop_BiTree(stack_BiTree* stack) //从二叉树栈顶取出一个元素
{
	BiTree node;
	node = &(stack->element[stack->top]);
	(stack->top)--;
	return node;
}


int getIndex(char theta) //获取theta所对应的索引
{

	int index = 0;
	switch (theta)
	{
	case '+':
		index = 0;
		break;
	case '-':
		index = 1;
		break;
	case '*':
		index = 2;
		break;
	case '/':
		index = 3;
		break;
	case '(':
		index = 4;
		break;
	case ')':
		index = 5;
		break;
	case '#':
		index = 6;
	default:break;
	}
	return index;
}

char getPriority(char theta1, char theta2)
//获取theta1与theta2之间的优先级
{
	const char priority[][7] =
		//算符间的优先级关系
	{
		{ '>', '>', '<', '<', '<', '<', '>' },
		{ '>', '>', '<', '<', '<', '<', '>' },
		{ '>', '>', '>', '>', '<', '<', '>' },
		{ '>', '>', '>', '>', '<', '<', '>' },
		{ '<', '<', '<', '<', '<', '=', '0' },
		{ '>', '>', '>', '>', '0', '>', '>' },
		{ '<', '<', '<', '<', '<', '0', '=' },
	};

	int index1 = getIndex(theta1);
	int index2 = getIndex(theta2);
	return priority[index1][index2];
}

//创建一个表达式二叉树
BiTree ExpTree_Create(BiTree left, BiTree right, char ch)
{
	BiTree T = (BiTree)malloc(sizeof(BiTreeNode));
	T->data = ch;
	T->leftChild = left;
	T->rightChild = right;
	return T;
}